const fs = require('fs');
const path = require('path');
const config = require('../config');

// 确保上传目录存在
const ensureUploadDir = () => {
    if (!fs.existsSync(config.UPLOAD_DIR)) {
        fs.mkdirSync(config.UPLOAD_DIR, { recursive: true });
    }
};

// 保存文件并返回 URL
const saveFile = (buffer, originalname) => {
    ensureUploadDir();
    const filename = `${Date.now()}_${originalname}`;
    const filePath = path.join(config.UPLOAD_DIR, filename);
    fs.writeFileSync(filePath, buffer);
    return `${config.SERVER_URL}/${config.UPLOAD_DIR}/${filename}`;
};

module.exports = { saveFile };